<template>
	<view>
		<!-- 血压仪 -->
		<!-- 	<view class="pressure">
			<view style="font-size:medium;word-break:break-all">设备名称：{{name}}</view>
			<view style="font-size:x-small;color:gray;word-break:break-all">设备ID：{{connectedDeviceId}}</view>
			<view class='pres-text'>压力值：{{testData.pressure}}</view>
			<view class='pres-text'>收缩压：{{testData.highPre}}</view>
			<view class='pres-text'>舒张压：{{testData.lowPre}}</view>
			<view class='pres-text'>心率：{{testData.heartRate}}</view>
		</view>
		<view class='pressure-btn'>

			<button @tap="baclkFun">返回</button>
		</view> -->
		<!-- <view class='pressure-info'>
			<scroll-view scroll-y="true" style='height:100%;width: 100%;' :scroll-top="scorollTop">
				<view class='info-list' v-for="(item,index) in pakInfoList" :key="index">{{item}}</view>
			</scroll-view>
		</view> -->


		<!-- 新版 -->
		<view class="equipmentbg">
			<navbar name="血压录入"></navbar>
			<view class="equipmentxy">
				<!-- <button @tap="startTest" :disabled="btndis">{{btnText}}</button> -->
				<view class="buzhou-one">
					<text class="bz-text">步骤1</text>请先确认设备处于工作状态，并打开手机蓝牙功能
				</view>
				<view class="buzhou-one" style="top:555upx">
					<text class="bz-text">步骤2</text>手机与设备连接成功后，请将臂带套在离手肘月
					2-3cm上端，身体保持放松，启动设备开始测量
				</view>
				<view class="buzhou-one" style="top:1140upx;">
					<text class="bz-text">步骤3</text>测量结束后请耐心等待测量结果
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				chooseType: 'Bioland-BPM', //血压计
				searching: false, //设备监听
				receiveText: '',
				name: '',
				connectedDeviceId: '',
				serviceId: '',
				notifyCharacteristicsId: '',
				writeCharacteristicsId: '',
				connected: true,
				//		idObj:{
				//			serviceId:'00001000-0000-1000-8000-00805F9B34FB',
				//			characteristicId:'00001001-0000-1000-8000-00805F9B34FB',
				//			characteristicId2:'00001002-0000-1000-8000-00805F9B34FB',
				//		},
				//		信息包内容
				sevicePackets: '',
				testShow: false,
				testData: {
					pressure: '',
					highPre: '--',
					lowPre: '--',
					heartRate: '--',
				},
				btnText: '开始测量',
				btndis: false,
				//判断是否主动断开
				activeClose: false,
				pakInfoList: [],
				scorollTop: 100
			}
		},
		onLoad(options) {
			this.BleInitialonlaod();
			this.Search()
			//	  屏幕保存常亮
			wx.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		onUnload() {
			console.log('页面隐藏')
			// 页面隐藏
			var that = this;
			wx.hideLoading()
			//  终止监听设备
			if (this.searching) {
				wx.stopBluetoothDevicesDiscovery({
					success: function(res) {
						that.searching = false
					}
				})
			}
			this.closeBleFun();
		},
		methods: {
			// 设备记录血压
			addRecord(healthData, mac, deviceId) {
				// 修改高低压
				healthData = JSON.parse(healthData)
				healthData.diastolicPre = healthData.lowPre; //低压
				healthData.systolicPre = healthData.highPre; //高压
				healthData = JSON.stringify(healthData)

				let _this = this,
					fdata = {
						deviceType: 'BLOOD_PRESSURE',
						recordTime: this.$basejs.thisdayFormat2(false, ''),
						inputType: 2, //1手动 2设备
						userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
						mac: mac, //设备mac
						deviceId: deviceId, //设备id
						healthDataId: '',
						healthData: healthData,
					};
				this.$api.post(global.apiUrls.addRecord, fdata).then(res => {
					if (res.data.code == 1000) {
						uni.showToast({
							title: res.data.message,
							duration: 2000
						});
						setTimeout(() => {
							// uni.navigateBack({
							// 	delta: 1
							// });
							_this.baclkFun()
						}, 2000);
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							duration: 2000
						});
					}
				}).catch(err => {})
			},
			// api存储电子秤数据
			tbEquipmentData(deviceId, equipmentData, mac) {
				let _this = this,
					fdata = {
						equipmentTypeId: 2, //设备类型1:体脂秤2：血压计
						deviceId: deviceId,
						equipmentData: equipmentData,
						mac: mac,
						userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId
					}
				this.$api.post(global.apiUrls.tbEquipmentData, fdata)
					.then(res => {
						if (res.data.code == 1000) { //成功
							_this.record(_this.itemCode, 100)
						} else {
							uni.showToast({
								title: res.data.message,
								icon: "none",
								duration: 2000
							});
						}
					}).catch(err => {})
			},
			Search() {
				wx.showLoading({
					title: '搜索设备中...',
				})
				var that = this
				if (!that.searching) {
					wx.closeBluetoothAdapter({
						complete: function(res) {
							console.log(res)
							wx.openBluetoothAdapter({
								success: function(res) {
									console.log(res)
									wx.getBluetoothAdapterState({
										success: function(res) {
											console.log(res)
										}
									})
									wx.startBluetoothDevicesDiscovery({
										allowDuplicatesKey: false,
										success: function(res) {
											console.log(res)
											that.searching = true;
										}
									})
								},
								fail: function(res) {
									wx.hideLoading()
									console.log(res)
									wx.showModal({
										title: '提示',
										content: '请检查手机蓝牙是否打开',
										showCancel: false,
										success: function(res) {
											uni.navigateBack({
												delta: 1
											});
											that.searching = false
										}
									})
								}
							})
						}
					})
				} else {
					wx.stopBluetoothDevicesDiscovery({
						success: function(res) {
							console.log(res)
							that.searching = false
						}
					})
				}
			},
			// 连接设备
			Connect(data) {
				var that = this
				//		chooseType: Bioland-BGM=>血糖仪       Bioland-BPM==>血压计
				let chT = this.chooseType;
				let urlPath = ''
				// if (chT == 'Bioland-BGM') {
				// 	urlPath = '../sugar/index?connectedDeviceId=' + data.deviceId + '&name=' + data.name
				// } else if (chT == 'Bioland-BPM') {
				// 	urlPath = '../pressure/index?connectedDeviceId=' + data.deviceId + '&name=' + data.name
				// } else if (chT == 'Bioland-IT') {
				// 	urlPath = '../thermometer/index?connectedDeviceId=' + data.deviceId + '&name=' + data.name
				// }
				wx.stopBluetoothDevicesDiscovery({
					success: function(res) {
						console.log(res)
						that.searching = false
					}
				})
				wx.showLoading({
					title: '连接设备中...',
				})
				wx.createBLEConnection({
					deviceId: data.deviceId,
					success: function(res) {
						console.log(res)
						wx.hideLoading()
						wx.showToast({
							title: '连接成功',
							icon: 'success',
							duration: 1000
						})
						that.BleInitial({
							connectedDeviceId: data.deviceId,
							name: data.name
						})

						// wx.redirectTo({
						// 	url: urlPath
						// })
					},
					fail: function(res) {
						console.log(res)
						wx.hideLoading()
						wx.showModal({
							title: '提示',
							content: '连接失败',
							showCancel: false,
							success: function(res) {
								// uni.navigateBack({
								// 	delta: 1
								// })
								that.baclkFun()
							},
						})
					}
				})
			},
			// 蓝牙初始化
			BleInitialonlaod() {
				let that = this;
				console.log('onLoad');
				wx.onBluetoothAdapterStateChange(function(res) {
					console.log(res)
					that.searching = res.discovering
					if (!res.available) {
						that.searching = false
					}
				})
				wx.onBluetoothDeviceFound(function(devices) {
					console.log('获取蓝牙设备') //蓝牙设备列表
					console.log(devices.devices[0]) //蓝牙设备列表
					console.log(devices.devices[0].name) //蓝牙设备列表
					console.log(devices.devices[0])
					let name = devices.devices[0].name
					if (name == that.chooseType) {
						that.Connect(devices.devices[0])
					}
				})
			},
			pakInfoFun(Text, data) {
				let paL
				paL = this.pakInfoList
				let inf
				inf = Text + data;
				let sT = this.scorollTop + 30
				paL.push(inf)
				this.pakInfoList = paL; //
				this.scorollTop = sT
			},
			//	断开连接
			closeBleFun() {
				let that = this;
				wx.closeBLEConnection({
					deviceId: this.connectedDeviceId,
					success: function() {
						console.log('close sucess')
						that.activeClose = true;
					}
				})
			},
			//	返回
			baclkFun() {
				this.closeBleFun();
				uni.navigateBack({
					delta: 1
				})
			},
			BlelinkFail() {
				let that = this;
				setTimeout(function() {
					//			判断,如果不是主动断开连接,则提示弹框;
					var pages = getCurrentPages();
					pages = pages.reverse();
					console.log(pages,322222222)
					pages = pages[0].route //当前页面url
					if (!that.activeClose&&pages == 'pages/subpackage/home/equipment/bloodPressure') {
						wx.showModal({
							title: '提示',
							showCancel: false,
							content: '蓝牙已断开连接，重新连接？',
							success(res) {
								if (res.confirm) {
									that.Search()
								}
							}
						})
					}
				}, 500)
			},
			//开始测量
			startTest() {
				//	发送'01'启动包
				if (this.testShow) {
					this.btnText = '正在测量...';
					wx.showLoading({
						title: '正在测量...',
					})
					this.testData.highPre = '--';
					this.testData.lowPre = '--';
					this.testData.heartRate = '--';
					this.btndis = true;
					this.Send('01');
				}
			},
			//	设备蓝牙匹配，发送数据包
			BleInitial(options) {
				wx.showLoading({
					title: '测量中...',
				})
				console.log('测量中...')
				var that = this;

				setTimeout(Times=>{
					that.startTest()
				},3000)
				that.name = options.name;
				that.connectedDeviceId = options.connectedDeviceId
				that.onchangeBLE()
				//获取蓝牙设备所有服务
				wx.getBLEDeviceServices({
					deviceId: that.connectedDeviceId,
					success: function(res) {
						console.log('获取设备所有服务')
						console.log(res.services)
						let seAr = res.services
						seAr.forEach(v => {
							if (v.uuid.indexOf("00001000") > -1) {
								that.serviceId = v.uuid;
							}
						})
						//服务有多个需要尝试连接最稳定的那个
						that.getBLEDeviceCharacteristics(that.serviceId)
					}
				})
				//		监听蓝牙连接状态:包括连接异常/断开连接
				wx.onBLEConnectionStateChange(function(res) {
					console.log(res.connected)
					that.connected = res.connected
					if (!res.connected) {
						that.BlelinkFail();
					}
				})

			},
			//	获取设备特征值
			getBLEDeviceCharacteristics(seId) {
				let that = this;
				wx.getBLEDeviceCharacteristics({
					deviceId: that.connectedDeviceId,
					serviceId: seId,
					success: function(res) {
						console.log('对应服务的特征值')
						console.log(res.characteristics)
						//              	 获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值
						let chaArr = res.characteristics
						res.characteristics.forEach(v => {
							if (v.uuid.indexOf("00001002") > -1) {
								that.notifyCharacteristicsId = v.uuid
							}
							if (v.uuid.indexOf("00001001") > -1) {
								that.writeCharacteristicsId = v.uuid
							}
						})
						that.notifyBLECharacteristicValueChange()
					},
					fail: function(error) {
						console.log('获取特征值失败')
						console.log(error)
					}
				})
			},
			//启用低功耗蓝牙设备特征值变化时的 notify 功能
			notifyBLECharacteristicValueChange() {
				var that = this;
				wx.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.connectedDeviceId,
					serviceId: that.serviceId,
					characteristicId: that.notifyCharacteristicsId,
					success(res) {
						console.log(res, '启用低功耗蓝牙设备监听成功')
						setTimeout(function() {
							that.Send('00')
						}, 1000)
					},
					complete(res) {},
					fail(error) {
						console.log(error, '启用低功耗蓝牙设备监听失败')
					}
				})
			},
			//监听低功耗蓝牙设备的特征值变化事件
			onchangeBLE() {
				var that = this;
				wx.onBLECharacteristicValueChange(function(res) {
					var receiveText = that.$basejs.buf2hex(res.value);
					console.log('返回数据' + receiveText)
					//		    '55':为包的开头部分,之后寻找其余部分,然后拼接
					let sePac = that.sevicePackets;
					//		     开头部分为:'55',为新包的开头部分
					let sT = receiveText.substr(0, 2)
					if (sT == '55') {
						sePac = receiveText
						that.sevicePackets = sePac
					} else {
						sePac += receiveText
						that.sevicePackets = sePac
					}
					//		    判断拼接后的包的长度,处理信息包数据
					//			15对=>30长度:信息包00
					//			8对=>16长度:过程包02
					//			14对=>28长度:结果包03
					//			5对=>10长度:错误包EEH&&结束包
					let type;
					type = sePac.substr(4, 2);
					//			判断是否为有效信息,是就进行处理
					if (
						(type == '00' && (sePac.length == 30 || sePac.length == 36)) ||
						(type == '02' && sePac.length == 16) ||
						(type == '03' && sePac.length == 28) ||
						(type == '05' && sePac.length == 20) ||
						((type == 'EE' || type == 'ee') && sePac.length == 20)
					) {
						//处理包
						that.packetsDataFun(sePac)
					}
				})
			},
			//	数据包处理
			packetsDataFun(value) {
				let that = this;
				//.信息包:00
				//.过程包:02
				//.结果包:03
				//.错误包:EE
				//.结束包:05
				let type = value.substr(4, 2)
				if (type == '00' && (value.length == 30 || value.length == 36)) {
					//	信息包不处理,用于判断
					that.testShow = true;
					that.pakInfoFun('接收数据(拼接后信息包00)：', value)
					// wx.hideLoading();
				} else if (type == '02' && value.length == 16) {
					let vl4 = this.handleResult(value.substr(10, 2))
					this.testData.pressure = vl4
					that.pakInfoFun('接收数据(拼接后过程包02)：', value)
				} else if (type == '03' && value.length == 28) {
					let vl1 = this.handleResult(value.substr(18, 2)) + this.handleResult(value.substr(20, 2));
					let vl2 = this.handleResult(value.substr(22, 2));
					let vl3 = this.handleResult(value.substr(24, 2));
					this.testData.highPre = vl1;
					this.testData.lowPre = vl2;
					this.testData.heartRate = vl3;
					this.btnText = '开始测量';
					let equipmentData = this.testData;
					equipmentData = JSON.stringify(equipmentData)
					// this.tbEquipmentData(this.connectedDeviceId, equipmentData, this.name) //保存记录
					this.addRecord(equipmentData, this.name, this.connectedDeviceId) //记录设备数据信息

					setTimeout(function() {
						that.btndis = false;
					}, 10000)
					that.pakInfoFun('接收数据(拼接后结果包03)：', value)
					// wx.hideLoading();
				} else if (type == '05' && value.length == 20) {
					this.btnText = '开始测量'
					that.pakInfoFun('接收数据(拼接后结束包05)：', value)
					// wx.hideLoading();
				} else if ((type == 'EE' || type == 'ee') && value.length == 20) {
					this.btnText = '开始测量'
					that.pakInfoFun('接收数据(拼接后错误包EE)：', value)
					// wx.hideLoading();
				}
			},
			//十六转十进制
			handleResult(data) {
				var val = '0x' + data;
				val = parseInt(val);
				return val
			},
			//	发包
			Send(threeArr) {
				var that = this;
				if (that.connected) {
					//发包内容
					let val = new Uint8Array(that.SendData(threeArr));
					console.log(
						'that.connectedDeviceId',
						that.connectedDeviceId,
						'that.serviceId',
						that.serviceId,
						'that.writeCharacteristicsId',
						that.writeCharacteristicsId,
						'val.buffer', val.buffer, '52666666666666666666666666')
					//发送数据到设备中
					wx.writeBLECharacteristicValue({
						deviceId: that.connectedDeviceId,
						serviceId: that.serviceId,
						characteristicId: that.writeCharacteristicsId,
						value: val.buffer,
						success: function(res) {
							console.log('发送成功')
							//        判断如果发送了'00'包还没有返回数据,则再次发送'00'包
							setTimeout(function() {
								if (!that.testShow) {
									that.Send('00')
								}
							}, 30000)
						},
						fail: function(res) {
							console.log('发送包失败')
						}

					})
				} else {
					// that.BlelinkFail()
				}
			},
			//	发包数据格式处理
			SendData(threeArr) {
				//		计算发包格式:
				//		1.把0--8位置的数相加然后在相加,再加+2==>从而求得位置9的数
				//		2.在分别转换成16进制
				//		获取日期
				let getT = new Date();
				console.log(getT, '55555555555555555555588888888888888888888888888')
				let Ty = '',
					Tm = '',
					Td = '',
					Th = '',
					Tmi = '',
					Ts = '',
					Tdate = '',
					Tadd = '';
				Ty = getT.getFullYear() % 100;
				Tm = getT.getMonth() + 1;
				Td = getT.getDate();
				Th = getT.getHours();
				Tmi = getT.getMinutes();
				Ts = getT.getSeconds();
				Tdate = Ty + '-' + Tm + '-' + Td + ' ' + Th + ':' + Tmi + ':' + Ts;
				//		获取包的最后一位数字
				Tadd = 90 + 10 + Number(threeArr) + Ty + Tm + Td + Th + Tmi + Ts + 2;
				//		这里高字节:大于255的数
				if (Tadd > 255) {
					//			获取最后两位
					Tadd = (Tadd % 255);
				}
				//		转十六进制
				threeArr = '0x' + threeArr.toString(16);
				Ty = '0x' + Ty.toString(16);
				Tm = '0x' + Tm.toString(16);
				Td = '0x' + Td.toString(16);
				Th = '0x' + Th.toString(16);
				Tmi = '0x' + Tmi.toString(16);
				Ts = '0x' + Ts.toString(16);
				Tadd = '0x' + Tadd.toString(16);
				let sendArr = ['0x5A', '0x0A', threeArr, Ty, Tm, Td, Th, Tmi, Ts, Tadd];
				console.log(sendArr)
				let val = new Uint8Array(sendArr);
				var receiveText = this.$basejs.buf2hex(val.buffer)
				if (threeArr == '0x00') {
					this.pakInfoFun('发送信息读取包00：', receiveText)
				} else if (threeArr == '0x01') {
					this.pakInfoFun('启动血压测量包01：', receiveText)
				}
				return sendArr;
			},
		}
	}
</script>

<style lang="scss">
	.equipmentbg {
		width: 100vw;
		min-height: 100vh;
		background: url(http://static.bsyjk.cn/equipmentbg/0DB19D05B0D1471BBCBDD70DAEDE2374.png)no-repeat;
		background-size: 100% 100%;

		.equipmentxy {
			width: 750upx;
			height: 1460upx;
			background: url(http://static.bsyjk.cn/equipmentxy/42E14DBB311D45DB920F23803A502758.png)no-repeat;
			background-size: 100% 100%;
			position: relative;
			color: #2EA7E0;
			text-align: center;

			.buzhou-one {
				width: 690upx;
				left: 50%;
				transform: translateX(-50%);
				font-size: 26upx;
				position: absolute;
				top: 74upx;

				.bz-text {
					font-size: 36upx;
					padding-right: 20upx;
				}
			}
		}
	}

	page {
		width: 100%;
		height: 100%;
		font-size: 30rpx;
	}

	.pressure {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		border-top: 1rpx solid #CCCCCC;
		height: auto;
	}

	.pressure .pres-text {
		width: 100%;
		padding: 10rpx;
		font-size: 30rpx;
	}

	.pressure-btn {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		height: auto;
	}

	.pressure-btn button {
		float: left;
		width: 46%;
		margin: 0 1%;
	}

	.pressure-info {
		width: 100%;
		position: absolute;
		top: 440rpx;
		left: 0;
		bottom: 10rpx;
		overflow: auto;
	}

	.pressure-info .info-list {
		width: 100%;
		height: auto;
		padding: 15rpx 10rpx;
		box-sizing: border-box;
	}
</style>
